package com.etop.jansing.controller;

import com.etop.jansing.dto.ResourceDto;
import com.etop.jansing.entities.Permission;
import com.etop.jansing.entities.ResourcePermission;
import com.etop.jansing.service.PermissionService;
import com.etop.jansing.service.ResourceService;
import com.etop.jansing.util.CommonUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 需要admin角色才可进入该controller
 * Created by jansing on 2015/10/26.
 */
@Controller
@RequestMapping("admin/permission")
@RequiresRoles("admin")
public class PermissionController extends BaseController {

    @Resource
    private PermissionService permissionService;
    @Resource
    private ResourceService resourceService;

    /**
     * 注入权限信息。这里的权限指的是资源权限对<br/>
     * 这个方法会在请求进入该控制器的某个方法前调用，<br/>
     * 比如修改权限：在进入edit()--POST 前会执行此方法返回一个permission，然后再将表单的数据放入这个permission<br/>
     *
     * @param tempId
     * @return
     */
    @ModelAttribute("resoPerm")
    public ResourcePermission get(@RequestParam(required = false, value = "id") String tempId) {
        try {
            Long id = Long.parseLong(tempId);
            if (id != null && id > 0) {
                return permissionService.getResoPermById(id);
            } else {
                return new ResourcePermission();
            }
        } catch (NumberFormatException e) {
            return new ResourcePermission();
        }
    }


    /**
     * 需要permission:list资源权限对才可进入该Action
     *
     * @param resoPerm
     * @param model
     * @return
     */
    @RequiresPermissions("permission:list")
    @RequestMapping(value = "/list", produces = "text/html;charset=utf-8")
    public String list(@ModelAttribute("resoPerm") ResourcePermission resoPerm, Model model) {
        ResourceDto rootResourceDto = resourceService.getRootResource(null);
        model.addAttribute("rootResourceDto", rootResourceDto);
        return "admin/permission/list";
    }

    @RequiresPermissions("permission:edit")
    @RequestMapping(value = "/edit", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String editPermission(Model model, @ModelAttribute("resoPerm") ResourcePermission resoPerm) {
        List<com.etop.jansing.entities.Resource> canGetPermission = resourceService.getCanGetPermission();
        List<Permission> permissionList = permissionService.getAllPermissions();
        model.addAttribute("resoPerm", resoPerm);
        model.addAttribute("canGetPermission", canGetPermission);
        model.addAttribute("permissionList", permissionList);
        return "/admin/permission/edit";
    }

    @RequiresPermissions("permission:edit")
    @RequestMapping(value = "/edit", produces = "text/html;charset=utf-8", method = RequestMethod.POST)
    public String savePermission(@ModelAttribute(value = "resoPerm") ResourcePermission resoPerm, HttpServletRequest request, Model model)
            throws Exception {
        String oldResoPermString = request.getParameter("oldResoPermString");
        //与已删除的权限也不能同名
        if (!oldResoPermString.equals(resoPerm.getResoPermString()) &&
                permissionService.getResoPermByResoPermString(resoPerm.getResoPermString()) != null) {
            log.error("-->该权限键值已存在");
            resoPerm.setResoPermString(oldResoPermString);
            return editPermission(model, resoPerm);
        }
        try {
            long resourceId = CommonUtils.getId(request.getParameter("resourceId"));
            long permissionId = CommonUtils.getId(request.getParameter("permissionId"));
            resoPerm.setResource(resourceService.getById(resourceId));
            resoPerm.setPermission(permissionService.getById(permissionId));
        }catch (NumberFormatException e){
            log.error("-->参数错误");
            return editPermission(model, resoPerm);
        }
        permissionService.saveOrUpdate(resoPerm);
        return "redirect:/admin/permission/list";
    }

    /**
     * 如果资源拥有该权限的资源权限对，则拒绝删除。
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("permission:delete")
    @RequestMapping(value = "/delete/{id}", produces = "text/html;charset=utf-8")
    public String deletePermission(@PathVariable("id") long id, Model model) {
        ResourcePermission resoPerm = permissionService.getResoPermById(id);
        if (permissionService.isUsing(resoPerm)) {
            //如果某个资源拥有该权限，即为被占用，此时不可删除
            log.error("-->该权限已被使用，请先在资源中解除对该权限的使用");
        } else {
            permissionService.delete(resoPerm);
        }
        return "redirect:/admin/permission/list";
    }
}
